#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.utils.text import capfirst
from django.core import urlresolvers

class Country(models.Model):
    """
    International Organization for Standardization (ISO) 3166-1 Country list
    
     * ``iso`` = ISO 3166-1 alpha-2
     * ``name`` = Official country names used by the ISO 3166/MA in capital letters
     * ``printable_name`` = Printable country names for in-text use
     * ``iso3`` = ISO 3166-1 alpha-3
     * ``numcode`` = ISO 3166-1 numeric
    
    Note::
        This model is fixed to the database table 'country' to be more general.
        Change ``db_table`` if this cause conflicts with your database layout.
        Or comment out the line for default django behaviour.
    
    """
    iso = models.CharField(_('ISO alpha-2'), max_length=2, primary_key=True)
    name = models.CharField(_('Official name (CAPS)'), max_length=128)
    printable_name = models.CharField(_('Country name'), max_length=128)
    iso3 = models.CharField(_('ISO alpha-3'), max_length=3, null=True)
    numcode = models.PositiveSmallIntegerField(_('ISO numeric'), null=True)
    
    region_module = models.CharField(max_length=255, blank=True)
    region_choices = models.CharField(max_length=255, blank=True)
    
    active = models.BooleanField(default=True)
    
    def has_regions(self):
        return (self.region_module != '' and self.region_choices != '') or len(self.regionentry_set.all())
    
    class Meta:
        db_table = 'country'
        verbose_name = _('Country')
        verbose_name_plural = _('Countries')
        ordering = ('name',)
        
    def __unicode__(self):
        return self.printable_name
    
    def get_ajax_url(self):
        return urlresolvers.reverse('region-codes',
            kwargs={'country': self.iso})
    
class PostalCode(models.Model):
    country = models.ForeignKey(Country)
    zip = models.CharField(max_length=15, blank=True, null=True, db_index=True)
    city = models.CharField(max_length=32, blank=True, null=True)
    state = models.CharField(max_length=5, blank=True, null=True)
    county = models.CharField(max_length=32, blank=True, null=True)
    zip_type = models.CharField(max_length=32, blank=True, null=True)
    lat = models.FloatField(blank=True, null=True)
    lng = models.FloatField(blank=True, null=True)
    
    def __unicode__(self):
        return u'%s %s' % (self.country, self.zip)

class RegionEntry(models.Model):
    country = models.ForeignKey(Country)
    name = models.CharField(max_length=128)
    code = models.CharField(max_length=10)

    class Meta:
        verbose_name_plural = _(u'region entries')
    
    def __unicode__(self):
        return self.name
